package com.conversationboard.serialisation;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.mapper.MapperWrapper;

/**
 * Uses Codehaus/Thoughtworks XStream, which uses reflection to build XML
 * documents from objects. This is used when we have some data not suitable for
 * storage in a relational database. We can store it in the database property
 * bag as an XML document. We can make XML documents by serialising from
 * objects. We can get the info back as objects when we deserialise.
 * 
 * @author Keith Watson
 * 
 */

public class XmlSerialiser<T> {

	/* Override the default XStream so that we can delete elements from classes and not have exceptions when XML that contain
	 * these elements is read */

	private XStream xStream = new XStream() {

		protected MapperWrapper wrapMapper(MapperWrapper next) {
			return new MapperWrapper(next) {

				public boolean shouldSerializeMember(Class definedIn, String fieldName) {
					return definedIn != Object.class ? super.shouldSerializeMember(definedIn, fieldName) : false;
				}

			};
		}

	};


	public void omitField(Class definedIn, String fieldName) {
		this.xStream.omitField(definedIn, fieldName);
	}


	public void setAlias(String name, Class cl) {
		xStream.alias(name, cl);
	}


	public String serialise(T o) {

		String xml = this.xStream.toXML(o);

		return xml;
	}


	public T deSerialise(String xml) {

		T object = (T) this.xStream.fromXML(xml);

		return object;

	}

}
